import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'
//  引入路由
import Home from '@/views/Home'
import Login from '@/views/Login'
import Register from '@/views/Register'
import Search from '@/views/Search'
import Detail from '@/views/Detail'
import AddCartSuccess from '@/views/AddCartSuccess'
import ShopCart from '@/views/ShopCart'
import Center from '@/views/Center'
import Pay from '@/views/Pay'
import PaySuccess from '@/views/PaySuccess'
import Trade from '@/views/Trade'

// 使用路由
Vue.use(VueRouter)

// 暴露router
const router = new VueRouter({
	// 滚动行为设置 每次路由跳转都会经过这里
	scrollBehavior() {
		// return 期望滚动到哪个的位置
		return { x: 0, y: 0 }
	},
	// 路由模式
	mode: 'history',
	// 配置路由
	routes: [
		{
			path: '/home',
			component: Home,
			name: 'Home',
		},
		{
			path: '/search',
			component: Search,
			name: 'Search',
		},
		{
			path: '/detail/:id',
			component: Detail,
			name: 'Detail',
		},
		{
			path: '/addcartsuccess',
			component: AddCartSuccess,
			name: 'AddCartSuccess',
		},
		{
			path: '/shopcart',
			component: ShopCart,
			name: 'ShopCart',
		},
		{
			path: '/center',
			component: Center,
			name: 'Center',
		},
		{
			path: '/pay',
			component: Pay,
			name: 'Pay',
		},
		{
			path: '/paysuccess',
			component: PaySuccess,
			name: 'PaySuccess',
		},
		{
			path: '/trade',
			component: Trade,
			name: 'Trade',
		},
		{
			path: '/login',
			component: Login,
			name: 'Login',
			// 当前路由匹配生效，这个meta参数就会生效 可以通过$route.meta获取其中参数
			meta: {
				isShowFooter: true,
			},
		},
		{
			path: '/register',
			component: Register,
			name: 'Register',
			meta: {
				isShowFooter: true,
			},
		},
		{
			// 除以上路径
			path: '*',
			// 重定向到home
			redirect: '/home',
		},
	],
})
// 要验证的组件
const AUTH_LIST = [
	'AddCartSuccess',
	'ShopCart',
	'Center',
	'Pay',
	'PaySuccess',
	'Trade',
]

router.beforeEach((to, from, next) => {
	// to 是对象 里面有跳转到目标地址的值
	// from 也是对象 里面有从哪里来
	// next是往下执行 渲染页面
	// 判断要跳转的路径 是否有要验证的组件
	if (AUTH_LIST.includes(to.name)) {
		if (store.state.user.token) {
			next()
		} else {
			alert('请登录后再试')
			// next对象写法 可以跳转到传参的路径
			next({
				name: 'Login',
				query: {
					redirect: to.path,
				},
			})
		}
	} else {
		next()
	}
})

export default router
